#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "show_info.h"
#include "table.h"
#include "read_buffer.h"
#include "meta_command.h"
#include "prepare_statement.h"
#include "execute_statement.h"



int main(int argc, char *argv[])
{
    setbuf(stdout, NULL);
    InputBuffer *input_buffer = new_input_buffer();
    if(argc < 2){
        printf("Must supply a database file\n");
        exit(EXIT_FAILURE);
    }
    Table *table = db_open(argv[1]);
    while (true)
    {
        // 读取指令
        print_prompt();
        read_input(input_buffer);

        // 判断是不是命令行指令
        if (input_buffer->buffer[0] == '.')
        {
            switch (do_meta_command(input_buffer, table))
            {
            case META_COMMAND_SUCCESS:
                continue;
            case META_COMMAND_UNRECOGNIZED_COMMAND:
                printf("Unrecognized command '%s'\n", input_buffer->buffer);
                continue;
            default:
                break;
            }
        }

        Statement statement;

        switch (prepare_statement(input_buffer, &statement))
        {
        case PREPARE_SUCCESS:
            break;
        case PREPARE_SYNTAX_ERROR:
            printf("Syntax error. Could not parse statement.\n");
            continue;
        case PREPARE_UNRECOGNIZED_STATEMENT:
            printf("Unrecognized keyword at start of '%s'.\n", input_buffer->buffer);
            continue;
        case PREPARE_STRING_TOO_LONG:
            printf("String is too long.\n");
            continue;
        case PREPARE_NEGATIVE_ID:
            printf("ID must be positive.\n");
            continue;
        default:
            continue;
            break;
        }
        
        switch (excute_statement(&statement, table))
        {
        case EXECUTE_SUCCESS:
            print_excute();
            break;
        case EXECUTE_TABLE_FULL:
            printf("Error: Table full.\n");
            break;
        case EXECUTE_DUPLICATE_KEY:
            printf("Error: Duplicate key.\n");
            break;
        default:
            break;
        }
        
    }
}